(ns ken.pu.web.search
    (:use [clojure.data.json :only (json-str write-json read-json)]
          [ken.pu.lucene-helper]
          [clojure.string :only (join)]))

(def *searcher*
    {:entity (mk-index-searcher "mycampus-entities.idx")
     :value (mk-index-searcher "mycampus-values.idx")})

(def *analyzer* (mk-analyzer))

(defn search
    ([q-str topk]
        (cond
          (empty? q-str) []
          :else (let [q (mk-simple-query :and *analyzer* "__all__" q-str)]
                    (index-search (:entity *searcher*) q topk))))
    ([q-str]
        (search q-str 100)))

(defn jsonify
    [data]
    (json-str {:data data}))

(defn jsonpify
    [data callback]
    (str callback "(" (jsonify data) ")"))

(defn suggest
    [q-str]
    (let [topk 5
          q (mk-simple-query :or *analyzer* "__all__" q-str)]
        (index-search (:value *searcher*) q topk)))

(defn suggest-fuzzy
    [q-str]
    (suggest (join " " (ngram q-str))))